package com.uroad.lib.widget.loadmore;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;

import com.uroad.lib.R;
import com.uroad.lib.adapter.rv.DividerItemDecoration;
import com.uroad.lib.adapter.rv.wrapper.LoadMoreWrapper;

/**
 * used to loadmore
 * Created by jiadong on 2016/11/11.
 */
public class LoadMoreRecyclerView extends RecyclerView {

    private LoadMoreWrapper mLoadMoreWrapper;
    private OnLoadMoreListener mOnLoadMoreListener;

    public LoadMoreRecyclerView(Context context) {
        super(context);
        init(context);
    }

    public LoadMoreRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public LoadMoreRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context){
        setLayoutManager(new LinearLayoutManager(context));
//        addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL_LIST));
    }

    public void startAnimation(Context context){
        Animation animation = AnimationUtils.loadAnimation(context, R.anim.listview_alpha_right_in);
        LayoutAnimationController controller = new LayoutAnimationController(animation);
        controller.setDelay(0.5f);
        controller.setOrder(LayoutAnimationController.ORDER_NORMAL);
        setLayoutAnimation(controller);
    }

    @Override
    public void setAdapter(Adapter adapter) {
        mLoadMoreWrapper = new LoadMoreWrapper(adapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.loadmore_footer);
        mLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mOnLoadMoreListener != null) {
                    mOnLoadMoreListener.onLoadMore();
                }
            }
        });
        super.setAdapter(mLoadMoreWrapper);
    }

    public void notifyDataSetChanged() {
        if (mLoadMoreWrapper != null) {
            mLoadMoreWrapper.notifyDataSetChanged();
        }
    }

    public void setCanLoadMore(boolean canLoadMore) {
        mLoadMoreWrapper.isCanLoadMore(canLoadMore);
    }

    public void setLoadMoreListener(OnLoadMoreListener moreListener) {
        this.mOnLoadMoreListener = moreListener;
    }

    public interface OnLoadMoreListener {
        public void onLoadMore();
    }
}
